package com.chinanet.utils.telnet;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

public class TelnetWork {

	private TelnetClient telnet = new TelnetClient();
	private InputStream in = null;
	private PrintStream out = null;
	private StringBuffer sbb = new StringBuffer();

	public Map<String, Object> init(Telnet_Attrsln telattrs) {
		Map<String, Object> outString = new HashMap<String, Object>();
		Map<String, Object> inString = new HashMap<String, Object>();
		try {
			telnet.connect(telattrs.getTbIpAddress(), 23);
			in = telnet.getInputStream();
			out = new PrintStream(telnet.getOutputStream());
			int i = login(telattrs.getTbUsername(), telattrs.getTbPassword(),
					telattrs.getSwitchboardIpAddress(),
					telattrs.getSwitchboardUsername(),
					telattrs.getSwitchboardPassword());
			if (i == 0) {
				in.close();
				out.close();
				telnet.disconnect();
				outString.put("flag", 0);
				outString.put("UnselectedPorts", inString.get("portname"));
				outString.put("rate", inString.get("rate"));
				outString.put("log", "用户名或密码错误");
				return outString;
			}
			try {
//				readUntil("<TZ-XJ-DSW-1.MAN.H3C12510F>");
				readUntil(">");
				write(telattrs.getCommand());
				readUntil("---- More ----");
				write("\r\n");
				while (readUntiltwo("---- More ----")) {
					write("\r\n");
				}
				write("quit");
			} catch (Exception e) {
				e.printStackTrace();
			}
			ManagerString ms =new ManagerString();

			inString = ms.getname(sbb.toString());
			in.close();
			out.close();
			telnet.disconnect();
			outString.put("flag", 1);
			outString.put("UnselectedPorts", inString.get("portname"));
			outString.put("rate", inString.get("rate"));
			outString.put("log", inString.get("portname")+" "+ inString.get("rate"));
			return outString;
		} catch (Exception e) {
			e.printStackTrace();
		}
		outString.put("flag", 0);
		outString.put("UnselectedPorts", "");
		outString.put("rate", "");
		outString.put("log", "timeout");
		return outString;
	}

	/**
	 * 登录
	 * @param tbUsername
	 * @param tbPassword
	 * @param switchboardIpAddress
	 * @param SwitchboardUsername
	 * @param SwitchboardPassword
	 * @return
	 */
	private int login(String tbUsername, String tbPassword,
			String switchboardIpAddress, String SwitchboardUsername,
			String SwitchboardPassword) {
		readUntil("Username:");
		write(tbUsername);
		readUntil("Password:");
		write(tbPassword);
		//TZ-JJ-SNL-AccessBoard-1.MAN
		if (readUntilerror("% Authentication failed.",">","\r\n")) {
			return 0;
		}
//		readUntil("TZ-JJ-SNL-AccessBoard-1.MAN>");
		readUntil(">");
		String telnetcommond = "telnet " + switchboardIpAddress;
		write(telnetcommond);
		readUntil("login:");
		write(SwitchboardUsername);
		readUntil("Password:");
		write(SwitchboardPassword);
//		<TZ-XJ-DSW-1.MAN.H3C12510F
		if (readUntilerror("login:",">","\r\n")) {
			return 0;
		}
		return 1;
	}

	/**
	 * 读取分析结果
	 * 
	 * @param pattern
	 * @return
	 */
	private String readUntil(String pattern) {
		try {
			char lastChar = pattern.charAt(pattern.length() - 1);
			StringBuffer sb = new StringBuffer();
			char ch = (char) in.read();
			while (true) {
				sb.append(ch);
				sbb.append(ch);
				if (ch == lastChar) {
					if (sb.toString().endsWith(pattern)) {
						return "";
					}
				}
				ch = (char) in.read();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 处理more
	 * 
	 * @param pattern
	 * @return
	 */
	private boolean readUntiltwo(String pattern) {
		try {
//			String aa = "<TZ-XJ-DSW-1.MAN.H3C12510F>";
			String aa=">";
			char lastChars = aa.charAt(aa.length() - 1);
			char lastChar = pattern.charAt(pattern.length() - 1);
			StringBuffer sb = new StringBuffer();
			char ch = (char) in.read();

			while (true) {
				sb.append(ch);
				sbb.append(ch);
				if (ch == lastChar) {
					if (sb.toString().endsWith(pattern)) {

						return true;
					}
				}
				if (ch == lastChars) {
					if (sb.toString().endsWith(aa)) {

						return false;
					}
				}
				ch = (char) in.read();

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 判断用户名和密码错误的情况
	 * 
	 * @param pattern
	 * @return
	 */
	public boolean readUntilerror(String pattern, String txt, String command) {
		try {
			char lastChar = pattern.charAt(pattern.length() - 1);
			char lastChars = txt.charAt(txt.length() - 1);
			StringBuffer sb = new StringBuffer();
			char ch = (char) in.read();
			while (true) {
				sb.append(ch);
				sbb.append(ch);
				if (ch == lastChar) {
					if (sb.toString().endsWith(pattern)) {
						return true;
					}
				}
				if (ch == lastChars) {
					if (sb.toString().endsWith(txt)) {
						write(command);
						return false;
					}
				}
				ch = (char) in.read();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 写操作
	 */
	private void write(String value) {
		try {
			out.println(value);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** * 关闭连接 */
	public void disconnect() {
		try {
			telnet.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
